package com.mifengs.mall.ui.map;

import android.graphics.Point;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.util.LocationUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MapSelectActivity extends BaseActivity implements AMapLocationListener ,AMap.OnCameraChangeListener ,GeocodeSearch.OnGeocodeSearchListener{

    @BindView(R.id.map_view)
    MapView mMapView;
    private AMap mAMap;
    private MyLocationStyle myLocationStyle;
    private static final int MAP_SCALE = 19;
    private AMapLocationClient mlocationClient;
    private MarkerOptions mCenterMarkerOptions;
    private LocationSource.OnLocationChangedListener mListener;
    private Marker mCenterMarker;
    private AMapLocationClientOption mLocationOption;
    private boolean isLocal = false;
    private LatLng mLoclatLng;
    private GeocodeSearch mGeocodeSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_select);
        ButterKnife.bind(this);
        setStatusColorAndMode(R.color.white, true);
        mMapView.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        setup();
    }

    /**
     * 配置地图信息
     */
    private void setup() {
        mAMap = mMapView.getMap();
        mAMap.getUiSettings().setZoomControlsEnabled(false);     // 设置不显示缩放控件
        mAMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);
        mAMap.moveCamera(CameraUpdateFactory.zoomTo(MAP_SCALE));  // 设置缩放等级
        mAMap.setOnCameraChangeListener(this);

        //地理搜索类
        mGeocodeSearch = new GeocodeSearch(this);
        mGeocodeSearch.setOnGeocodeSearchListener(this);

        dingwei();
    }


    @OnClick({R.id.ll_back, R.id.ll_right, R.id.fl_dingwei})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.ll_right:

                break;
            case R.id.fl_dingwei:
                againLoc();
                break;
        }
    }

    /**
     * 在屏幕中心添加一个Marker ,这个mark放哪  去哪里去搜索
     */
    private void addMarkerInScreenCenter() {
        if (mCenterMarkerOptions == null) {
            LatLng latLng = mAMap.getCameraPosition().target;
            Point screenPosition = mAMap.getProjection().toScreenLocation(latLng);
            mCenterMarkerOptions = new MarkerOptions().icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.ic_mid_loc))
                    .zIndex(100)
                    .draggable(false);
            mCenterMarker = mAMap.addMarker(mCenterMarkerOptions);
            mCenterMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        } else {
            LatLng latLng = mAMap.getCameraPosition().target;
            Point screenPosition = mAMap.getProjection().toScreenLocation(latLng);
            mCenterMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        }
    }


    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
        mLocationOption = null;
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图

    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图

    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }


    public void dingwei(){
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(getContext());
            mlocationClient.setLocationListener(this);
            mLocationOption = LocationUtil.getDefaultOption();
            mlocationClient.setLocationOption(mLocationOption);
            mlocationClient.startLocation();
        }
    }


    @Override
    public void onLocationChanged(AMapLocation amaplocation) {
        if (amaplocation != null) {
            if (amaplocation != null && amaplocation.getErrorCode() == 0) {
                if (!isLocal) {
                    mLoclatLng = new LatLng(amaplocation.getLatitude(), amaplocation.getLongitude());
                 //   mAMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));
                   // mlocationClient.stopLocation();
                    mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLoclatLng, MAP_SCALE), new AMap.CancelableCallback() {
                        @Override
                        public void onFinish() {
                            addMarkerInScreenCenter();
                            mlocationClient.stopLocation();
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
                    isLocal = true;
                }
            } else {
//                String errText = "failed to locate," + amaplocation.getErrorCode() + ": "
//                        + amaplocation.getErrorInfo();
//                ToastUitl.showLong(errText);
            }
        }
    }

    /**
     * 点击图中定位标志定位
     */
    private void againLoc() {
        mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLoclatLng, MAP_SCALE));
        if(mlocationClient!=null)
        mlocationClient.startLocation();
        isLocal = false;
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        LatLng latLng = new LatLng(cameraPosition.target.latitude,cameraPosition.target.longitude);
        getAddressByLatlng(latLng);
    }


    private void getAddressByLatlng(LatLng latLng) {
        //逆地理编码查询条件：逆地理编码查询的地理坐标点、查询范围、坐标类型。
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500f, GeocodeSearch.AMAP);
        //异步查询
        mGeocodeSearch.getFromLocationAsyn(query);
    }

    //得到逆地理编码异步查询结果
    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
        String formatAddress = regeocodeAddress.getFormatAddress();
        ToastUitl.show(formatAddress, Toast.LENGTH_LONG);
        getLatlngByAddress(formatAddress);
    }


    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
        List<GeocodeAddress> addressList = geocodeResult.getGeocodeAddressList();
    }


    private void getLatlngByAddress(String name){
        GeocodeQuery query = new GeocodeQuery(name,"0086");
        mGeocodeSearch.getFromLocationNameAsyn(query);
    }

}
